document.addEventListener('DOMContentLoaded', function() {
    // 文件上传预览
    document.getElementById('photo').addEventListener('change', function(e) {
        const fileName = e.target.files[0]?.name || '选择文件';
        e.target.nextElementSibling.textContent = fileName;
    });

    //添加编辑按钮点击监听事件
    $('#employeeTableBody').on('click', '.btn-info', function() {
        const empId = $(this).data("emp-id");
        console.log('编辑员工ID:', empId);
        // 在这里可以添加更多的逻辑，例如填充模态框中的表单数据
        //显示id的div
        $("#empIdDiv").show();
        $("#empId").val(empId);
        getEmployeeById(empId);
    });

    //通过员工Id获取员工信息
    function getEmployeeById(empId) {
        let method = "detail";
        $.ajax({
            url: "http://localhost:25080/empsys",
            type: 'GET',
            data: { method, empId },
            dataType: 'json',
            success: function(data) {
                console.log("获取员工信息成功:"+ data);
                $('#name').val(data.empName);
                $('#department').val(data.depId);
                $('#position').val(data.position);
                $('#hireDate').val(data.startDate);
                $('#phone').val(data.phone);
            }
        })
    }

    // 表单验证和提交
    document.getElementById('employeeForm').addEventListener('submit', function(e) {
        //阻止表单默认提交
        e.preventDefault();
        
        // 获取表单数据
        const formData = new FormData();
        let method = "edit";
        formData.append('method', method);
        let empName = document.getElementById('name').value;
        formData.append('empName', empName);
        let departmentId = document.getElementById('department').value;
        formData.append('departmentId', departmentId);
        let position = document.getElementById('position').value;
        formData.append('position', position);
        let hireDate = document.getElementById('hireDate').value;
        formData.append('hireDate', hireDate);
        let phone = document.getElementById('phone').value;
        formData.append('phone', phone);
        let photo = document.getElementById('photo').files[0] || null;
        formData.append('photo', photo);

        // 手机号码格式验证
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!phoneRegex.test(phone)) {
            alert('请输入正确的手机号码');
            return;
        }

        //部门验证
        if(departmentId=="-1"){
            alert('请选择部门')
            return;
        }

        // TODO: 发送数据到服务器
        console.log('提交的员工数据:', formData);

        $.ajax({
            url: 'http://localhost:25080/empsys',
            type: 'POST',
            data: formData,
            processData: false, //告诉jQuery不要去处理发送的数据
            contentType: false, //告诉jQuery不要去设置Content-Type请求头
            dataType: 'json',
            success: function(data) {
                if (data.code == 200) {
                    alert(data.msg);
                }
            },
            error: function(error) {
                console.error('员工信息提交失败:', error);
                alert('员工信息提交失败');
            },
        });

        // 关闭模态框并重置表单
        $('#employeeModal').modal('hide');
        e.target.reset();
        document.querySelector('.custom-file-label').textContent = '选择文件';
        location.reload();
    });

    // 删除确认
    let employeeToDelete = null;
    
    // 点击删除按钮时显示确认框
    $("#employeeTableBody").on("click", ".btn-danger", function() {
        
        employeeToDelete = $(this).data("emp-id");
        $('#deleteModal').modal('show');
    })

    // 确认删除
    document.querySelector('#deleteModal .btn-danger').addEventListener('click', function() {
        if (employeeToDelete) {
            // TODO: 发送删除请求到服务器
            $.ajax({
                url: "http://localhost:25080/empsys",
                type: "GET",
                data: {
                    method: "delete",
                    empId: employeeToDelete 
                },
                dataType: "json",
                success: function(data) {
                    alert(data.msg);
                    location.reload();
                },
                error: function() {
                    alert("删除失败，请稍后重试");
                }
            });


            employeeToDelete = null;
        }
        $('#deleteModal').modal('hide');
    }); 
});